<template>
  <a-modal :width="700" v-model:visible="showAddShopDialog" title="添加店铺" :footer="false" title-align="start" :mask-closable="false" @cancel="closedDialog">
    <div class="add-shop-wrap">
      <a-steps :current="currentStep" style="margin-bottom: 30px">
        <a-step>添加店铺</a-step>
        <a-step>基础API授权</a-step>
        <a-step>广告授权</a-step>
      </a-steps>
      <div class="add-shop-con">
        <template v-if="currentStep == 1">
          <a-form style="width: 500px" ref="shopFormRef" :model="shopInfo" :rules="rulesUser">
            <a-form-item field="shopName" label="店铺名称">
              <a-input v-model="shopInfo.shopName" placeholder="请输入店铺名称" allow-clear />
            </a-form-item>
            <a-form-item field="shopMasterIds" label="店长">
              <a-select v-model="shopInfo.shopMasterIds" placeholder="选择店长" allow-search allow-clear>
                <a-option v-for="(user, i) in userList" :key="i" :value="user.id" :label="user.userName" />
              </a-select>
            </a-form-item>
            <a-form-item label="品牌">
              <a-select v-model="shopBrandParams" placeholder="选择品牌" multiple value-key="code" allow-search allow-clear>
                <a-option v-for="(brand, i) in brandList" :key="i" :value="brand" :label="brand.name" />
              </a-select>
            </a-form-item>
            <a-form-item field="region" label="区域">
              <a-select v-model="shopInfo.region" @change="changeRegion">
                <a-option value="北美地区" label="北美地区" />
                <a-option value="欧洲地区" label="欧洲地区" />
                <a-option value="远东地区" label="远东地区" />
              </a-select>
            </a-form-item>
            <a-form-item field="marketplaceIds" label="站点">
              <a-space direction="vertical">
                <a-checkbox :model-value="checkedAll" :indeterminate="indeterminate" @change="handleChangeAll">全选</a-checkbox>
                <a-checkbox-group v-model="shopInfo.marketplaceIds" @change="handleChange">
                  <a-checkbox :value="market.marketplaceId" v-for="market in marketList" :key="market.marketplaceId">{{ market.marketplaceName }}</a-checkbox>
                </a-checkbox-group>
              </a-space>
            </a-form-item>
          </a-form>
        </template>
        <template v-if="currentStep == 2">
          <div class="auth-w">
            <p>当前环境授权</p>
            <p>适合场景：亚马逊店铺和ERP登录在同一设备同一浏览器窗口（同一IP）</p>
            <div class="flex-c-end auth-url">
              <a-button type="primary" size="mini" @click="openUrl(authUrl)">授权</a-button>
            </div>
          </div>
          <div class="auth-w">
            <p>其他环境授权</p>
            <p>适合场景：当前环境不是亚马逊店铺常用环境</p>
            <p>操作方法：复制授权链接后，在授权店铺的常用环境下，点击浏览器“+”，进入此链接授权</p>
            <div class="flex-c-end auth-url">
              <p class="text-limit" style="margin-right: 10px">{{ authUrl }}</p>
              <CopyText :val="authUrl">
                <template #copyCon>
                  <a-button type="primary" size="mini">复制授权链接</a-button>
                </template>
              </CopyText>
            </div>
          </div>
        </template>
        <template v-if="currentStep == 3">
          <p>站点：</p>
          <a-table class="table-singe-line" size="mini" :columns="tableColumns" :pagination="false" :bordered="false" :data="shopMarketList" style="margin-top: 20px">
            <template #marketplaceId="{ record }">
              <p>{{ record.marketplaceName }}({{ record.marketplaceCode }})</p>
            </template>
            <template #shopClerks="{ record }">
              <a-select v-model="record.shopClerks" multiple allow-clear style="width: 300px">
                <a-option v-for="(item, index) in userList" :key="index" :value="item.id" :label="item.userName" />
              </a-select>
            </template>
            <template #baseAuthMap="{ record }">
              <div class="flex-c" style="width: 100px">
                <CopyText :val="adAuthUrlMap[record.marketplaceId]">
                  <template #copyCon>
                    <p class="highlight cursor">复制链接去授权</p>
                  </template>
                </CopyText>
              </div>
            </template>
          </a-table>
        </template>
      </div>
      <div class="flex-c-end">
        <a-space>
          <a-button size="small" @click="closedDialog" v-if="currentStep == 1">取消</a-button>
          <a-button type="primary" size="small" @click="submitShop" :loading="summitLoading" v-if="currentStep == 1">保存并下一步</a-button>
          <a-button type="primary" size="small" @click="getAuthStatus" :loading="summitLoading" v-if="currentStep == 2">检测是否授权成功</a-button>
          <a-button type="primary" size="small" @click="submitMarket" :loading="summitLoading" v-if="currentStep == 3">保存</a-button>
        </a-space>
      </div>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { getOrganizesUser, getShopMarketByRegion, createShop, getAmazonPiiAuthUrl, getShopInfo, getAmazonAdAuthUrl, updateShopMarkets } from '@/api/system'
  import { getBrandList } from '@/api/product'
  import { Message } from '@arco-design/web-vue'
  onMounted(async () => {
    getUserList()
    getAllBrandList()
    getMarketsByRegion()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
  })

  const currentStep = ref(1)
  const showAddShopDialog = ref(props.isShow)
  const shopInfo = ref<any>({
    region: '北美地区',
  })
  const tableColumns: Array<any> = [
    {
      title: '站点',
      dataIndex: 'marketplaceId',
      slotName: 'marketplaceId',
    },
    {
      title: '币种',
      dataIndex: 'currency',
      slotName: 'currency',
    },
    {
      title: '店员',
      dataIndex: 'shopClerks',
      slotName: 'shopClerks',
    },
    {
      title: '广告授权',
      dataIndex: 'baseAuthMap',
      slotName: 'baseAuthMap',
    },
  ]
  const userList = ref<Array<any>>([])
  const brandList = ref<Array<any>>([])
  const shopBrandParams = ref<Array<any>>([])
  const marketList = ref<Array<any>>([])
  const shopMarketList = ref<Array<any>>([])
  const adAuthUrlMap = ref<any>({})
  const indeterminate = ref(false)
  const checkedAll = ref(false)
  const shopFormRef = ref()
  const summitLoading = ref(false)
  const authUrl = ref()
  let shopDetail: any = {}
  let shopId = ''
  const rulesUser = ref({
    shopName: [{ required: true, message: '请输入店铺名称' }],
    shopMasterIds: [{ required: true, message: '请选择店长' }],
    region: [{ required: true, message: '请选择区域' }],
    marketplaceIds: [{ required: true, message: '请选择站点' }],
  })

  // 全选
  function handleChangeAll(value: any) {
    indeterminate.value = false
    if (value) {
      checkedAll.value = true
      shopInfo.value.marketplaceIds = marketList.value.map((el) => el.marketplaceId)
    } else {
      checkedAll.value = false
      shopInfo.value.marketplaceIds = []
    }
  }
  function handleChange(values: any) {
    if (values.length === marketList.value.length) {
      checkedAll.value = true
      indeterminate.value = false
    } else if (values.length === 0) {
      checkedAll.value = false
      indeterminate.value = false
    } else {
      checkedAll.value = false
      indeterminate.value = true
    }
  }
  // 根据区域获取站点
  async function getMarketsByRegion() {
    const res: any = await getShopMarketByRegion({ region: shopInfo.value.region })
    marketList.value = res?.data || []
  }
  // 切换区域
  function changeRegion() {
    marketList.value = []
    checkedAll.value = false
    shopInfo.value.marketplaceIds = []
    getMarketsByRegion()
  }
  // 获取所有用户列表
  async function getUserList() {
    const res: any = await getOrganizesUser({
      pageNum: 1,
      pageSize: 1000,
    })
    userList.value = res?.data?.records || []
  }
  // 获取所有品牌列表
  async function getAllBrandList() {
    const res: any = await getBrandList({
      pageNum: 1,
      pageSize: 1000,
    })
    brandList.value = res?.data?.records || []
  }
  // 获取亚马逊Pii授权地址
  async function getPiiAuthUrl() {
    const res: any = await getAmazonPiiAuthUrl({ id: shopId })
    authUrl.value = res?.data
  }
  //新窗口打开地址
  function openUrl(url: any) {
    window.open(url, '_block')
  }
  // 检测隐私授权状态
  async function getAuthStatus() {
    summitLoading.value = true
    const res: any = await getShopInfo({ id: shopId })
    summitLoading.value = false
    shopDetail = res?.data || {}
    if (res?.data?.baseAuth == 1) {
      Message.success('授权成功')
      currentStep.value = 3
      setShopMarketList()
    } else {
      Message.warning('授权未成功，请稍后再检测')
    }
  }
  // 设置站点列表信息
  async function setShopMarketList() {
    shopMarketList.value = shopDetail?.shopMarkets || []
    let marketplaceIds = shopMarketList.value.map((el) => el.marketplaceId)
    const res: any = await getAmazonAdAuthUrl({ marketplaceIds: marketplaceIds?.join(',') })
    adAuthUrlMap.value = res?.data || {}
  }

  // 关闭
  function closedDialog() {
    if (currentStep.value == 1) {
      shopInfo.value = {}
      shopFormRef.value.clearValidate()
      emit('closed')
    } else {
      emit('success')
    }
    showAddShopDialog.value = false
  }
  // 提交店铺信息
  async function submitShop() {
    let valid = await shopFormRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return
    let brandList = shopBrandParams.value.map((el) => {
      return {
        brandCode: el.code,
        brandName: el.name,
        brandId: el.id,
      }
    })
    let params = {
      marketplaceIds: shopInfo.value.marketplaceIds,
      region: shopInfo.value.region,
      shopMasterIds: [shopInfo.value.shopMasterIds],
      shopName: shopInfo.value.shopName,
      shopBrandParams: brandList,
    }
    summitLoading.value = true
    const res: any = await createShop(params)
    summitLoading.value = false
    if (!res) return
    shopId = res.data
    currentStep.value = 2
    getPiiAuthUrl()
  }
  // 批量修改站点信息
  async function submitMarket() {
    let shopMarketItems = shopMarketList.value.map((el) => {
      return {
        id: el.id,
        shopClerkIds: el.shopClerks,
        clerkType: 2,
      }
    })
    summitLoading.value = true
    const res: any = await updateShopMarkets({ shopMarketItems: shopMarketItems })
    summitLoading.value = false
    if (res) {
      Message.success('保存成功！')
      closedDialog()
    }
  }
</script>
<style lang="less" scoped>
  .add-shop-wrap {
    padding: 0 20px;
    .add-shop-con {
      height: 400px;
    }
  }
  .auth-w {
    padding: 10px;
    margin-bottom: 15px;
    border: 1px solid var(--color-border);
    line-height: 20px;
    .auth-url {
      margin-top: 20px;
    }
  }
  .arco-typography {
    margin-bottom: 0;
  }
  :deep(.arco-icon-check) {
    color: #fff;
  }
</style>
